<template>
  <a-form-model-item
    :label="label"
    :prop="name ? name : prop"
    :rules="fnRules()"
  >
    <a-range-picker
      class="readonly"
      v-if="readonly"
      v-model="value"
      :placeholder="placeholder"
      :format="format"
      :valueFormat="valueFormat"
      disabled
      style="width: 100%;background-color:#fff;color: rgba(0, 0, 0, 0.65);cursor: auto;"
    />
    <a-range-picker
      v-else
      v-model="value"
      :showTime="{
        format: format,
        hourStep: hourStep,
        minuteStep: minuteStep,
        secondStep: secondStep
      }"
      :mode="['time', 'time']"
      :placeholder="placeholder"
      :format="format"
      :disabled="disabled"
      :valueFormat="valueFormat"
      dropdownClassName="rangeTimePicker"
      :defaultOpenValue="[moment('00:00:00', 'HH:mm:ss'), moment('00:00:00', 'HH:mm:ss')]"
      :disabledDate="disabledDate"
      :disabledTime="disabledTime"
      style="width: 100%;"
      @change="handleChange"
    />
  </a-form-model-item>
</template>

<script>
import moment from 'moment';
export default {
  name: 'RangeTimePicker',
  props: {
    // 绑定的对象
    form: {
      type: Object,
      default: () => {
        return {};
      }
    },
    // 绑定对象的属性
    prop: {
      type: String,
      default: 'attribute'
    },
    // 循环中使用的检验值
    name: {
      type: String,
      default: ''
    },
    // 文字
    label: {
      type: String,
      default: ''
    },
    // 显示日期格式
    format: {
      type: String,
      default: 'HH:mm:ss'
    },
    // 生成数据日期格式
    valueFormat: {
      type: String,
      default: ''
    },
    hourStep: {
      type: Number,
      default: 1
    },
    minuteStep: {
      type: Number,
      default: 59
    },
    secondStep: {
      type: Number,
      default: 59
    },
    placeholder: {
      type: Array,
      default: () => {
        return ['开始时间', '结束时间'];
      }
    },
    // 禁止操作
    disabled: {
      type: Boolean,
      default: false
    },
    // 只读
    readonly: {
      type: Boolean,
      default: false
    },
    // 默认必填
    isRequired: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    parentData: function() {
      const arr = this.prop.split('.');
      const key = arr[arr.length - 1];
      return this.analysisAttribute(this.form)[key];
    }
  },
  watch: {
    parentData: {
      handler: function(val) {
        if (val && val.length > 0) {
          this.value = [];
          for (var i = 0; i < val.length; i++) {
            if (val[i]) {
              this.value.push(moment(val[i], 'HH:mm:ss'));
            } else {
              this.value.push(moment());
            }
          }
        } else {
          this.initialization();
        }
      },
      immediate: true
    }
  },
  data() {
    var validatorTimeIdentical = (rule, value, callback) => {
      if (value && value.length === 2) {
        if (value[0] === value[1]) {
          callback(new Error('开始时间与结束时间不能相同！'));
        } else {
          callback();
        }
      } else {
        if (this.isRequired) {
          callback(new Error('请选择' + this.label));
        } else {
          callback();
        }
      }
    };
    return {
      value: [],
      validatorTimeIdentical: validatorTimeIdentical
    };
  },
  methods: {
    moment,
    /**
     * [initialization 初始化（重置面板选中值）]
     * @return {[type]} [description]
     */
    initialization() {
      this.value = [];
      this.value.push(moment('00:00:00', 'HH:mm:ss'));
      this.value.push(moment('00:59:59', 'HH:mm:ss'));
      this.$nextTick(() => {
        this.value = [];
      });
    },
    /**
     * [fnRules 必填校验]
     * @return {[type]} [description]
     */
    fnRules() {
      if (this.isRequired) {
        return { required: true, validator: this.validatorTimeIdentical, trigger: 'change' };
      } else {
        return { validator: this.validatorTimeIdentical, trigger: 'change' };
      }
    },

    handleChange(e) {
      var aTime = [];
      for (var i = 0; i < e.length; i++) {
        aTime.push(moment(e[i]));
      }
      if (aTime[0]) {
        aTime[0].set('minutes', 0);
        aTime[0].set('seconds', 0);
        aTime[0] = moment(aTime[0]).format('HH:mm:ss');
      }
      if (aTime[1]) {
        aTime[1].set('minutes', 59);
        aTime[1].set('seconds', 59);
        aTime[1] = moment(aTime[1]).format('HH:mm:ss');
      }
      this.$emit('change', aTime);
      this.analysisAttribute(this.form, aTime);
    },
    /**
     * [analysisAttribute 根据字符串获取末级对象]
     * @param  {[type]} object [读取的对象]
     * @param  {[type]} val    [末级对象的具体属性赋值val（空值输出末级对象）]
     * @return {[type]}        [description]
     */
    analysisAttribute(object, val) {
      var arr = this.prop.split('.');
      let index = 0;
      const length = arr.length;
      while (object != null && index < length - 1) {
        object = object[arr[index]];
        index++;
      }
      if (val || val === 0 || val === '') {
        if (length !== 1) {
          index++;
        }
        object[arr[index]] = val;
      } else {
        return object;
      }
    },
    /**
     * [disabledTime 不限制选择时间]
     * @param  {[type]} _    [description]
     * @param  {[type]} type [前后时间start | end]
     * @return {[type]}      [description]
     */
    disabledTime(_, type) {
      if (type === 'start') {
        return {
          disabledHours: () => [],
          disabledMinutes: () => this.range(1, 60),
          disabledSeconds: () => this.range(1, 60)
        };
      } else {
        return {
          disabledHours: () => [],
          disabledMinutes: () => this.range(0, 59),
          disabledSeconds: () => this.range(0, 59)
        };
      }
    },
    disabledDate(current) {
      return false;
    },
    /**
     * [range 生成连续的数字数组]
     * @param  {[type]} start [起]
     * @param  {[type]} end   [止]
     * @return {[type]}       [description]
     */
    range(start, end) {
      const result = [];
      for (let i = start; i < end; i++) {
        result.push(i);
      }
      return result;
    }
  }
};
</script>
<style>
  .rangeTimePicker .ant-input-disabled{
    background-color:#fff;color: rgba(0, 0, 0, 0.65);cursor: auto;
  }
  .rangeTimePicker .ant-calendar-range.ant-calendar-time .ant-calendar-time-picker-inner{
    padding-top: 0;
  }
  .rangeTimePicker .ant-calendar-time .ant-calendar-footer .ant-calendar-time-picker-btn{
    display: none;
  }
</style>
